package o2o.delivery.controller;

import com.jinyou.utils.common.AjaxResult;
import com.jinyou.utils.common.ValidateUtil;
import com.jinyouapp.common.utils.map.Geohash;
import lombok.extern.slf4j.Slf4j;
import o2o.cache.shop.ShopMemory;
import o2o.cache.user.UserInfoMemory;
import o2o.dao.PO.order.OrderInfoGoods;
import o2o.company.model.ShopInfo;
import o2o.dao.PO.user.UserInfo;
import o2o.delivery.model.to.ThridPlateDeliveryOrderTO;
import o2o.delivery.model.vo.DeliveryOrderVO;
import o2o.delivery.model.vo.DeliveryUserAuthVO;
import o2o.delivery.service.DeliveryAuthService;
import o2o.delivery.service.DeliveryOrderService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Jahnke【1029777564@qq.com】
 * @ClassName DeliveryAuthController
 * @Description:
 * @date 2021/1/26 15:27
 * @Version 1.0
 */
@RestController
@Slf4j
public class DeliveryAuthController {

    @Autowired
    private DeliveryAuthService deliveryAuthService;
    @Autowired
    private DeliveryOrderService deliveryOrderService;

    @RequestMapping("delivery/user/login")
    public String login(String token, String username, String password) {
        if (StringUtils.isEmpty(deliveryAuthService.getKey(token))) {
            return AjaxResult.errorResult("token错误");
        }
        UserInfo userInfo = UserInfoMemory.getInstance().getUserInfo(username);
        if (userInfo == null) {
            return AjaxResult.errorResult("未查询到有效的用户信息！");
        }
        // 判断密码
        if (StringUtils.isEmpty(password) || !password.equalsIgnoreCase("myt" + (username.substring(5)))) {
            return AjaxResult.errorResult("密码错误！");
        }

        // 返回基础用户信息和店铺信息
        ShopInfo shopInfo = ShopMemory.getInstance().getShopByUsername(username);
        if (shopInfo == null) {
            return AjaxResult.errorResult("当前帐号尚未开通店铺");
        }
        DeliveryUserAuthVO info = new DeliveryUserAuthVO();
        info.setUsername(username).setName(StringUtils.isEmpty(userInfo.getName()) ? shopInfo.getShopName() : userInfo.getName());
        info.setShopId(shopInfo.getId()).setShopLat(shopInfo.getLat()).setShopLng(shopInfo.getLng()).setShopCity(shopInfo.getCity()).setShopAddr(shopInfo.getAddress());
        info.setShopName(shopInfo.getShopName()).setShopPhone(shopInfo.getTelephone());
        return AjaxResult.successResult(info);
    }

    @RequestMapping("delivery/orders/addOrder")
    public String addDeliveryOrder(String token, ThridPlateDeliveryOrderTO to) {
        String key = null;
        if (StringUtils.isEmpty(key = deliveryAuthService.getKey(token))) {
            return AjaxResult.errorResult("token错误");
        }
        // 数据监测
        if (StringUtils.isEmpty(to.getSource())) {
            return AjaxResult.errorResult("订单来源错误");
        }
        UserInfo userInfo = UserInfoMemory.getInstance().getUserInfo(to.getUsername());
        if (userInfo == null) {
            return AjaxResult.errorResult("未查询到有效的用户信息！");
        }
        if (!Geohash.isChinaLocal(to.getEndLat(), to.getEndLng()) || !Geohash.isChinaLocal(to.getStartLat(), to.getStartLng())) {
            return AjaxResult.errorResult("收获/取货地址经纬度不能为空");
        }
        if (StringUtils.isEmpty(to.getEndName()) || StringUtils.isEmpty(to.getEndPhone()) || StringUtils.isEmpty(to.getEndAddr())) {
            return AjaxResult.errorResult("收货人姓名或者联系方式不能为空");
        }
        if (StringUtils.isEmpty(to.getStartAddr()) || StringUtils.isEmpty(to.getStartPhone())) {
            return AjaxResult.errorResult("商铺地址或者联系方式不能为空");
        }
        if (ValidateUtil.isAbsList(to.getGoodsList())){
            for (OrderInfoGoods goods : to.getGoodsList()) {
                if (goods.getName()==null){
                    return AjaxResult.errorResult("商品名称为空");
                }
                if (goods.getImageUrl()!=null&&!goods.getImageUrl().matches("(http|https)://(?!(\\.jpg|\\.png)).+?(\\.jpg|\\.png)")){
                    return AjaxResult.errorResult("图片地址有误（https://**/*.png）");
                }
                if (goods.getTotalCount()==null || goods.getTotalCount()<=0){
                    return AjaxResult.errorResult("商品数量应为正整数");
                }
                if (goods.getTotalPrice()!=null && goods.getTotalPrice()<=0){
                    return AjaxResult.errorResult("商品总价不能为负数或0");
                }
            }
        }
        if (ValidateUtil.isNotAbsLong(to.getShopId())){
            log.info("参数错误{店铺id为空}");
        }
        if (ValidateUtil.isNotAbsDouble(to.getOrderPrice())||ValidateUtil.isNotAbsDouble(to.getGoodsPrice())){
            log.info("参数错误{订单金额或商品金额为空}");
        }
        if (StringUtils.isEmpty(to.getStartName())){
            log.info("参数错误{取货商家名称为空}");
        }
        DeliveryOrderVO deliveryOrderVO = null;
        try {
            deliveryOrderVO = deliveryOrderService.addDeliveryOrder(key, to);
        } catch (Exception e) {
            log.info("添加配送单失败，原因==>{}",e.getMessage());
            return AjaxResult.errorResult(e.getMessage());
        }
        return AjaxResult.successResult(deliveryOrderVO);
    }

    // 获取订单信息
    @RequestMapping("delivery/order/status/query")
    public String getOrderInfo(String token, String source, String originOrderNo, String plateOrderNo) {
        if (StringUtils.isEmpty(deliveryAuthService.getKey(token))) {
            return AjaxResult.errorResult("token错误");
        }

        DeliveryOrderVO deliveryOrderVO = null;
        try {
            deliveryOrderVO = deliveryOrderService.getDeliveryOrderInfo(source, originOrderNo, plateOrderNo);
        } catch (Exception e) {
            return AjaxResult.errorResult(e.getMessage());
        }

        return AjaxResult.successResult(deliveryOrderVO);
    }

    // 订单取消
    @RequestMapping("delivery/order/formalCancel")
    public String cancelOrder(String token, String source, String originOrderNo, String plateOrderNo, String cancelReason) {
        if (StringUtils.isEmpty(deliveryAuthService.getKey(token))) {
            return AjaxResult.errorResult("token错误");
        }

        try {
            deliveryOrderService.cancelOrder(source, originOrderNo, plateOrderNo, cancelReason);
        } catch (Exception e) {
            return AjaxResult.errorResult(e.getMessage());
        }

        return AjaxResult.successResult();
    }
}
